package com.cxh.rmsq.ui.fragment.self;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.cxh.rmsq.R;
import com.cxh.rmsq.db.model.BaseResultListBean;
import com.cxh.rmsq.db.model.CommunityContent;
import com.cxh.rmsq.im.IMManager;
import com.cxh.rmsq.model.Result2;
import com.cxh.rmsq.net.RetrofitUtil;
import com.cxh.rmsq.ui.adapter.self.CircleListAdapter;
import com.cxh.rmsq.ui.fragment.BaseFragment;
import com.cxh.rmsq.utils.GlideEngine;
import com.cxh.rmsq.utils.MyUtils;
import com.cxh.rmsq.utils.ToastUtils;
import com.cxh.rmsq.viewmodel.SocialCircleViewModel;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnExternalPreviewEventListener;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.MaterialHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.RequestBody;

/**
 * 动态
 */
public class CommunityTrendsFragment extends BaseFragment implements CircleListAdapter.OnCustomClickListener {

    private SmartRefreshLayout refreshList;
    private RecyclerView recyclerView;
    private CircleListAdapter listAdapter;
    private static final String ARG_PARAM1 = "param1";
    private int page = 1;
    private SocialCircleViewModel socialCircleViewModel;
    private List<CommunityContent> dataList = new ArrayList<>();

    private String mParam1;
    private final ArrayList<LocalMedia> imagesMediaList = new ArrayList<>();


    public CommunityTrendsFragment() {
        // Required empty public constructor
    }


    public static CommunityTrendsFragment newInstance(String param1) {
        CommunityTrendsFragment fragment = new CommunityTrendsFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_community_trends;
    }

    @Override
    protected void onInitView(Bundle savedInstanceState, Intent intent) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        socialCircleViewModel = ViewModelProviders.of(this).get(SocialCircleViewModel.class);

        refreshList = findView(R.id.refresh_list);
        recyclerView = ((RecyclerView) findView(R.id.rv_list));

//        LinearLayoutManager mRecyclerViewLayoutManager2 = new LinearLayoutManager(getActivity());
//        mRecyclerViewLayoutManager2.setOrientation(LinearLayoutManager.VERTICAL);
//        recyclerView.setLayoutManager(mRecyclerViewLayoutManager2);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        listAdapter = new CircleListAdapter(3, this);
        listAdapter.setEmptyView(View.inflate(getActivity(), R.layout.empty_data_layout, null));
//        listAdapter.setHasStableIds(true);
        recyclerView.setAdapter(listAdapter);

//        listAdapter.setOnItemClickListener(new OnItemClickListener() {
//            @Override
//            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
//
//            }
//        });
        listAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                switch (view.getId()) {
                    case R.id.iv_like:
                        int type = 0;
                        if (listAdapter.getData().get(position).isLiked() == 1) {//已点赞
                            type = 0;
                        } else {
                            type = 1;
                        }
                        HashMap<String, Object> paramsMap = new HashMap<>();
                        paramsMap.put("busId", listAdapter.getData().get(position).getId());
                        paramsMap.put("userId", IMManager.getInstance().getCurrentId());
                        paramsMap.put("type", 1);//1动态2评论
                        paramsMap.put("isLiked", type);//1:点赞 0：取消
                        paramsMap.put("bdzUserId", listAdapter.getData().get(position).getUserId());//被点赞用户id,
                        RequestBody body = RetrofitUtil.createJsonRequest(paramsMap);
                        socialCircleViewModel.commentLiked(body);
                        int finalType = type;
                        socialCircleViewModel.commentLiked().observe(getActivity(), new Observer<Result2<String>>() {
                            @Override
                            public void onChanged(Result2<String> result) {
                                if (result.code == 200) {
//                                    if (finalType ==1){
//                                        ToastUtils.showToast("点赞成功");
//                                    }
                                    if ("1".equals(mParam1)) {
                                        socialCircleViewModel.getCommunityPage(IMManager.getInstance().getCurrentId(), "", page, 10);
                                    } else {
                                        socialCircleViewModel.getSubscriberCommunityPage(IMManager.getInstance().getCurrentId(), "", page, 10);
                                    }
//                                    dataList.set(position, newData.get(position));
                                }
                            }
                        });
                        break;
                }
            }
        });

        refreshList.resetNoMoreData();
        refreshList.setRefreshHeader(new MaterialHeader(getActivity()));
        refreshList.setRefreshFooter(new ClassicsFooter(getActivity()));
        refreshList.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                if ("1".equals(mParam1)) {
                    socialCircleViewModel.getCommunityPage(IMManager.getInstance().getCurrentId(), "", page, 10);
                } else {
                    socialCircleViewModel.getSubscriberCommunityPage(IMManager.getInstance().getCurrentId(), "", page, 10);
                }
                refreshLayout.finishLoadMore();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                dataList.clear();
                listAdapter.setNewInstance(null);
                if ("1".equals(mParam1)) {
                    socialCircleViewModel.getCommunityPage(IMManager.getInstance().getCurrentId(), "", page, 10);
                } else {
                    socialCircleViewModel.getSubscriberCommunityPage(IMManager.getInstance().getCurrentId(), "", page, 10);
                }
            }
        });
        initData();
    }

    private void initData() {
        page = 1;
        dataList.clear();
        listAdapter.setNewInstance(null);
        if ("1".equals(mParam1)) {
            socialCircleViewModel.getCommunityPage(IMManager.getInstance().getCurrentId(), "", page, 10);
            socialCircleViewModel.getCommunityPage().observe(this, new Observer<Result2<BaseResultListBean>>() {
                @Override
                public void onChanged(Result2<BaseResultListBean> result) {
//                Log.e("total", result.data.getTotal() + "");
                    if (refreshList.isRefreshing()) {
                        refreshList.finishRefresh();
                    }
                    if (result.data != null) {
                        if (page == 1) {
                            listAdapter.setNewInstance(result.data.getList());
                            if (result.data.getList().size() < 10) {
                                refreshList.setEnableLoadMore(false);
                            } else {
                                refreshList.setEnableLoadMore(true);
                            }

                        } else {
                            if (result.data.getList().size() > 0) {
                                listAdapter.addData(result.data.getList());
                                refreshList.setEnableLoadMore(true);
                            } else {
//                            listAdapter.getLoadMoreModule().loadMoreEnd(false);
//                                listAdapter.getLoadMoreModule().loadMoreComplete();
                                refreshList.setEnableLoadMore(false);
                                refreshList.finishLoadMoreWithNoMoreData();
                            }

                        }
                        dataList.addAll(result.data.getList());
                        Log.e("datalist.size", dataList.size() + "");
                        listAdapter.notifyDataSetChanged();

                    }

                }
            });
        } else {
            socialCircleViewModel.getSubscriberCommunityPage(IMManager.getInstance().getCurrentId(), "", page, 10);
            socialCircleViewModel.getSubscriberCommunityPage().observe(this, new Observer<Result2<BaseResultListBean>>() {
                @Override
                public void onChanged(Result2<BaseResultListBean> result) {
//                Log.e("total", result.data.getTotal() + "");
                    if (refreshList.isRefreshing()) {
                        refreshList.finishRefresh();
                    }
                    if (result.data != null) {
                        if (page == 1) {
                            listAdapter.setNewInstance(result.data.getList());
                            if (result.data.getList().size() < 10) {
                                refreshList.setEnableLoadMore(false);
                            } else {
                                refreshList.setEnableLoadMore(true);
                            }

                        } else {
                            if (result.data.getList().size() > 0) {
                                listAdapter.addData(result.data.getList());
                                refreshList.setEnableLoadMore(true);
                            } else {
                                refreshList.setEnableLoadMore(false);
//                            listAdapter.getLoadMoreModule().loadMoreEnd(false);
//                            listAdapter.getLoadMoreModule().loadMoreComplete();
                                refreshList.finishLoadMoreWithNoMoreData();
                            }

                        }
                        dataList.addAll(result.data.getList());
                        Log.e("datalist.size", dataList.size() + "");
                        listAdapter.notifyDataSetChanged();

                    }

                }
            });
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        refreshList.autoRefresh();
    }

    @Override
    public void onItemClick(int position, @Nullable CommunityContent data) {
//        startActivity(
//                new Intent(getActivity(), PreViewImgOrVideoActivity.class)
//                                        .putExtra("type", data.getFileType())
//                        .putExtra("url", data.getFiles()));
        int pos = 0;
        imagesMediaList.clear();
        if (!TextUtils.isEmpty(data.getFiles())) {
            if (data.getFiles().contains(",")) {//多张

                for (int i = 0; i < MyUtils.toList(data.getFiles()).size(); i++) {
                    LocalMedia localMedia = new LocalMedia();
                    localMedia.setPath(MyUtils.toList(data.getFiles()).get(i));
                    imagesMediaList.add(localMedia);
                }
                pos = position;
            } else {
                LocalMedia localMedia = new LocalMedia();
                localMedia.setPath(data.getFiles());
                imagesMediaList.add(localMedia);
                pos = 0;
            }
        }

        // 预览图片、视频、音频
        PictureSelector.create(getActivity())
                .openPreview()
                .setImageEngine(GlideEngine.createGlideEngine())
                .isPreviewFullScreenMode(true)
//                .isPreviewZoomEffect(true, recyclerView)
                .setExternalPreviewEventListener(new OnExternalPreviewEventListener() {
                    @Override
                    public void onPreviewDelete(int position) {

                    }

                    @Override
                    public boolean onLongPressDownload(Context context, LocalMedia media) {
                        return false;
                    }
                })
                .startActivityPreview(pos, false, imagesMediaList);
    }

    @Override
    public void onItemLongClick(int position, @Nullable CommunityContent data) {
        new XPopup.Builder(getActivity())
                .dismissOnTouchOutside(true)
                .dismissOnBackPressed(true)
                .asBottomList("", new String[]{"下载"}, new OnSelectListener() {
                    @Override
                    public void onSelect(int position, String text) {
                        if (data.getPictureDownload() == 1) {
                            if (data.getFileType() == 1) {//图片
                                if (!TextUtils.isEmpty(data.getFiles())) {
                                    if (data.getFiles().contains(",")) {//多张
                                        MyUtils.downloadImage(getActivity(), MyUtils.toList(data.getFiles()).get(position));
                                    } else {
                                        MyUtils.downloadImage(getActivity(), data.getFiles());
                                    }
                                }
                            } else {
                                MyUtils.downloadFromNetwork(getActivity(), data.getFiles());
                            }
                        } else {
                            ToastUtils.showToast("不允许下载！");
                        }
                    }
                }).show();
    }


    @Override
    public void onGroupClick(int position, @Nullable CommunityContent data) {

    }
}